package com.project.baseTest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

public class CustomRealm extends AuthorizingRealm {

    public CustomRealm(){
        //创建凭证匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置加密算法
        matcher.setHashAlgorithmName("md5");
        //设置散列次数
        matcher.setHashIterations(512);
        //设置加密的编码，为true表示Hex编码，false用Base64
        matcher.setStoredCredentialsHexEncoded(true);
        //将realm设置凭证管理器
        this.setCredentialsMatcher(matcher);

    }

    /**
     * 授权的方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //得到主体，也是用户名
      String userName= principalCollection.getPrimaryPrincipal().toString();
      if("tam".equals(userName)){
            //创建授权对象
          SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
          //给用户授予角色，授权后，该用户拥有这些角色集合（只能放字符串集合）
          authorizationInfo.addRoles(List.of("custom","manager","order"));
          //给用户授予指定的权限
          authorizationInfo.addStringPermission("user:create");
          authorizationInfo.addStringPermission("order:*");


          return authorizationInfo;
      }

        return null;
    }

    /**
     *认证的方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //得到登陆主体的用户名
     String name  =authenticationToken.getPrincipal().toString();

     if("tam".equals(name)){
         //返回认证对象，第一参数:主体，第二个参:密码，第三个参：realm名称
         return new SimpleAuthenticationInfo(name,"49fc681cb4abb9921b9e60cc1f53e26e", ByteSource.Util.bytes("wxc".getBytes()),this.getName());
     }


        return null;
    }
}
